//
//  NaGesture.swift
//  Screen
//
//  Created by Natsu on 1/4/17.
//  Copyright © 2017 alex.chih. All rights reserved.
//

import UIKit

class NaGesture: NSObject
{
    var superView:UIView?
    var superController:UIViewController?
    
    public func setup(view:UIView, controlelr:UIViewController)
    {
        superView = view
        superController = controlelr
        
        let swipeLeft = UISwipeGestureRecognizer(target: self, action:  #selector(tappedRightButton) )
        swipeLeft.direction = .left
        
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(tappedLeftButton) )
        swipeLeft.direction = .left
        
        superView?.addGestureRecognizer(swipeLeft)
        superView?.addGestureRecognizer(swipeRight)
    }
    
    func tappedRightButton(sender:Any)
    {
        let selectedIndex = superController?.tabBarController?.selectedIndex
        let aryViewController = superController?.tabBarController?.viewControllers
        
        if selectedIndex! < (aryViewController?.count)! - 1
        {
            let fromView = superController?.tabBarController?.selectedViewController?.view
            let toView = superController?.tabBarController?.viewControllers?[selectedIndex! + 1].view
            
            UIView.transition(from: fromView!, to: toView!, duration: 0.5, options: .transitionFlipFromRight, completion: { (state) in
                if state
                {
                    self.superController?.tabBarController?.selectedIndex = selectedIndex! + 1
                }
            })
        }
    }
    
    func tappedLeftButton(sender:Any)
    {
        let selectedIndex = superController?.tabBarController?.selectedIndex
        
        if selectedIndex! > 0
        {
            let fromView = superController?.tabBarController?.selectedViewController?.view
            let toView = superController?.tabBarController?.viewControllers?[selectedIndex! - 1].view
            
            UIView.transition(from: fromView!, to: toView!, duration: 0.5, options: .transitionFlipFromLeft, completion: { (state) in
                if state
                {
                    self.superController?.tabBarController?.selectedIndex = selectedIndex! - 1
                }
            })
        }
    }
}
